package com.sise.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sise.bean.CodeMsg;
import com.sise.bean.ProductInfoBean;
import com.sise.config.MyServerConfig;
import com.sise.entity.ProductInfo;
import com.sise.mapper.ProductInfoMapper;
import com.sise.mapper.ProductTypeMapper;
import com.sise.mapper.StoreInfoMapper;
import com.sise.service.IProductInfoService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * @author zj
 */
@Service
public class ProductInfoServiceImpl extends ServiceImpl<ProductInfoMapper, ProductInfo> implements IProductInfoService {

    @Resource
    private MyServerConfig serverConfig;

    @Resource
    private ProductInfoMapper productInfoMapper;

    @Resource
    private StoreInfoMapper storeInfoMapper;

    @Resource
    private ProductTypeMapper productTypeMapper;

    @Value("${upload.locationPicture}")
    private String locationPicture;

    @Value("${upload.pictureResourceHandler}")
    private String pictureResourceHandler;

    @Override
    public boolean save(ProductInfo productInfo) {
        int tag = productInfoMapper.insert(productInfo);
        return tag == 1;
    }

    @Override
    public boolean deleteById(Integer productId) {
        int tag = productInfoMapper.deleteById(productId);
        return tag == 1;
    }

    @Override
    public boolean deleteByIdList(List<Integer> productIdList) {
        int tag = productInfoMapper.deleteBatchIds(productIdList);
        return tag > 0;
    }

    @Override
    public boolean updateById(ProductInfo productInfo) {
        int tag = productInfoMapper.updateById(productInfo);
        return tag == 1;
    }

    @Override
    public ProductInfo findById(Integer productId) {
        return productInfoMapper.selectById(productId);
    }

    @Override
    public List<ProductInfo> findByProductNameLike(String productName) {
        return productInfoMapper.findByProductNameLike(productName);
    }

    @Override
    public List<ProductInfo> findUpAll(Integer storeId) {
        return productInfoMapper.findUpAll(storeId);
    }

    @Override
    public List<ProductInfo> findDownAll(Integer storeId) {
        return productInfoMapper.findDownAll(storeId);
    }

    @Override
    public List<ProductInfo> findAll() {
        return productInfoMapper.selectList(null);
    }

    @Override
    public List<ProductInfoBean> findByStoreTransformation(Integer storeId) {
        QueryWrapper<ProductInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        List<ProductInfo> productInfoList = productInfoMapper.selectList(queryWrapper);
        List<ProductInfoBean> productInfoBeanList = new ArrayList<>();
        for (ProductInfo productInfo : productInfoList) {
            ProductInfoBean productInfoBean = new ProductInfoBean();
            productInfoBean.setStore(storeInfoMapper.selectById(productInfo.getStoreId()).getStoreName());
            productInfoBean.setProductType(productTypeMapper.selectById(productInfo.getProductTypeId()).getProductTypeName());
            productInfoBean.setProductInfo(productInfo);
            productInfoBeanList.add(productInfoBean);
        }
        return productInfoBeanList;
    }

    @Override
    public List<ProductInfo> findUpProductByStoreIdAndProductTypeId(Integer storeId, Integer productTypeId) {
        QueryWrapper<ProductInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("store_id", storeId)
                .eq("product_type_id", productTypeId)
                .eq("product_status", "上架");
        return productInfoMapper.selectList(queryWrapper);
    }

    @Override
    public boolean increaseStock(Integer productId, Integer number) {
        int tag = productInfoMapper.increaseStock(productId, number);
        return tag == 1;
    }

    @Override
    public boolean decreaseStock(Integer productId, Integer number) {
        int tag = productInfoMapper.decreaseStock(productId, number);
        return tag == 1;
    }

    @Override
    public CodeMsg addProductInfo(MultipartFile multipartPicture, ProductInfo productInfo) {
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().concat("_");
        String fileName = uuid.concat(Objects.requireNonNull(multipartPicture.getOriginalFilename()));
        String fileServerPath = serverConfig.getUrl() +
                pictureResourceHandler.substring(0, pictureResourceHandler.lastIndexOf("/") + 1).concat(fileName);
        productInfo.setProductIcon(fileServerPath);
        File saveFile = new File(locationPicture, fileName);
        try {
            multipartPicture.transferTo(saveFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        productInfo.setProductMonthSales(0);
        productInfo.setProductPraiseRate(0f);
        int count = productInfoMapper.insert(productInfo);
        if (count == 1) {
            return new CodeMsg().setCode(200).setMsg("商品数据添加成功！");
        } else {
            return new CodeMsg().setCode(400).setMsg("商品数据添加失败！");
        }
    }

    @Override
    public List<ProductInfo> findByStoreId(Integer storeId) {
        if (storeId.equals(-1)) {
            return productInfoMapper.selectList(null);
        } else {
            QueryWrapper<ProductInfo> productInfoQueryWrapper = new QueryWrapper<>();
            productInfoQueryWrapper.eq("store_id", storeId);
            return productInfoMapper.selectList(productInfoQueryWrapper);
        }
    }

    @Override
    public void addProductLike(Integer productId) {
        productInfoMapper.addProductLike(productId);
    }

    @Override
    public void cancelProductLike(Integer productId) {
        productInfoMapper.cancelProductLike(productId);
    }

    @Override
    public CodeMsg<List<ProductInfo>> searchProduct(String search, Integer current) {
        Page<ProductInfo> productInfoIPage = new Page<>(current, 10);
        QueryWrapper<ProductInfo> productInfoQueryWrapper = new QueryWrapper<>();
        productInfoQueryWrapper.lambda().like(ProductInfo::getProductName, search);
        productInfoIPage = productInfoMapper.selectPage(productInfoIPage, productInfoQueryWrapper);
        List<ProductInfo> productInfoList = productInfoIPage.getRecords();
        if (productInfoList.isEmpty()) {
            return new CodeMsg<List<ProductInfo>>().setCode(400).setMsg("没有搜索到你的商品").setData(null);
        }
        if (productInfoIPage.hasNext()) {
            return new CodeMsg<List<ProductInfo>>().setCode(200).setMsg("查询成功,存在下一页").setData(productInfoList);
        } else {
            return new CodeMsg<List<ProductInfo>>().setCode(201).setMsg("查询成功，不存在下一页").setData(productInfoList);
        }
    }
}
